#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>

using namespace std;

int g_val = 10000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void* start_routine(void* args)
{
    string name = static_cast<char*>(args);
    while (1)
    {
        pthread_mutex_lock(&lock);
        if (g_val > 0)
        {
            cout << "I am  pthread process,g_val : " << g_val << " " << name << endl;
            g_val--;

            pthread_mutex_unlock(&lock);
            usleep(500);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
}

int main()
{
    pthread_t pid1, pid2, pid3, pid4, pid5, pid6;

    pthread_create(&pid1, NULL, start_routine, (void*)"thread1");
    pthread_create(&pid2, NULL, start_routine, (void*)"thread2");
    pthread_create(&pid3, NULL, start_routine, (void*)"thread3");
    pthread_create(&pid4, NULL, start_routine, (void*)"thread4");
    pthread_create(&pid5, NULL, start_routine, (void*)"thread5");
    pthread_create(&pid6, NULL, start_routine, (void*)"thread6");

    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);
    pthread_join(pid3, NULL);
    pthread_join(pid4, NULL);
    pthread_join(pid5, NULL);
    pthread_join(pid6, NULL);

    return 0;
}